<script setup>
import _ from 'lodash'
import TreeItemName from './tree-item-name.vue';
import {onMounted, reactive, ref, toRefs, watch} from "vue";
import {api} from "@jzl/api";

const emit = defineEmits(['close']);
const props = defineProps({
  rid: {
    type: Number,
    default: null
  },
  show: {
    type: Boolean,
    default: false
  }
})

const {
  items,
  loading,
  form,
  expandedKeys,
  checkedKeys,
  treeSetting,
  list,
  pagination
} = toRefs(reactive({
  items: [],
  loading: false,

  form: {
    name: '',
    status: "0",
  },
  expandedKeys: [],
  checkedKeys: [],
  treeSetting: {
    children: 'subs',
    label: 'name'
  },

  list: [],
  pagination: {
    current: 1,
    pageSize: 10,
    total: 0
  }
}))
// const formRef = ref(null)
// const menutreeRef = ref(null)
const selectedtreeRef = ref(null)
const selectedtreeT2Ref = ref(null)
const selectedtreeT3Ref = ref(null)
const selectedtreeT9Ref = ref(null)

onMounted(() => {
  init()
})

watch(() => props.show, (val) => {
  if (val) init()
})

const init = async () => {
  await initInfo();
  pagination.value.current = 1;
  await refresh();

  // this.$refs.menutree.filter();
  selectedtreeRef.value.filter();
  selectedtreeT2Ref.value.filter();
  selectedtreeT3Ref.value.filter();
  selectedtreeT9Ref.value.filter();
}

const initInfo = async () => {
  if (props.rid) {
    // this.$refs.mform && this.$refs.mform.resetFields();
    let data = await api.role.getRole(props.rid, {disabled: true});

    if (data) {
      form.value = data;
      items.value = _.get(data, 'menutree.items', []);
      checkedKeys.value = _.get(data, 'menutree.selected', []);
      refreshData();
    } else {
      $jui.toast('操作失败，请稍后再试！');
    }
  }
}

const refresh = async () => {

  loading.value = true;
  let data = await api.role.getRoleUsers(props.rid, {
    page: pagination.value.current,
    pageSize: pagination.value.pageSize
  });

  loading.value = false;
  pagination.value.total = _.get(data, 'count', 0);
  list.value = _.get(data, 'rows', []);
}

const refreshData = () => {
  if (items.value?.length) {
    for (let i = 0; i < items.value.length; i++) {
      items.value[i].disabled = true;
      let it = items.value[i];
      expandedKeys.value.push(it.tid);
    }
  }
}

const _remove = async (id) => {
  let ret = await api.role.disassociateUsers(id);

  if (ret) {
    await refresh();
  }
}

const handleRemove = (it) => {

  if (!it || !it.id) {
    return;
  }
  $jui.confirm(`此操作将移除该用户【${it.admin?.nickname || it.admin?.loginname || ''}】, 是否继续?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    _remove(it.id);
  }).catch(() => {
    $jui.toast({
      type: 'info',
      message: '已取消操作'
    });
  });
}

const close = (flag) => {
  emit('close', flag);
}

const handleMenuFilter = (value, data, node) => {
  let tty = _.get(data, 'tty');
  return tty === 1;
}

const handleMenuFilterT2 = (value, data, node) => {
  let tty = _.get(data, 'tty');
  return tty === 2;
}

const handleMenuFilterT3 = (value, data, node) => {
  let tty = _.get(data, 'tty');
  return tty === 3;
}

const handleMenuFilterT9 = (value, data, node) => {
  let tty = _.get(data, 'tty');
  return tty === 9;
}
</script>

<template>
  <div class="associate-wrap">
    <div class="associate-body">
      <div class="associate-item">
        <div class="associate-item-title">角色【{{ form.name }}】下功能菜单树：</div>

        <div class="role-menu-tree">
          <perfect-scrollbar
            class="mb-tree"
            :settings="{}"
            style="height: 100%;">
            <h6>已分配-后台管理菜单</h6>
            <el-tree
              ref="selectedtreeRef"
              class="menu-custom-tree tree-empty-image"
              :data="items"
              :check-strictly="true"
              node-key="tid"
              :highlight-current="true"
              :props="treeSetting"
              :default-expanded-keys="selectedKeys"
              :filter-node-method="handleMenuFilter">
              <template #default="{ node, data }">
                <tree-item-name :data="data"></tree-item-name>
              </template>
            </el-tree>
            <h6>已分配-电脑端菜单</h6>
            <el-tree
              ref="selectedtreeT3Ref"
              class="menu-custom-tree tree-empty-image"
              :data="items"
              :check-strictly="true"
              node-key="tid"
              :highlight-current="true"
              :props="treeSetting"
              :default-expanded-keys="selectedKeys"
              :filter-node-method="handleMenuFilterT3">
              <template #default="{ node, data }">
                <tree-item-name :data="data"></tree-item-name>
              </template>
            </el-tree>
            <h6>已分配-手机端菜单</h6>
            <el-tree
              ref="selectedtreeT2Ref"
              class="menu-custom-tree tree-empty-image"
              :data="items"
              :check-strictly="true"
              node-key="tid"
              :highlight-current="true"
              :props="treeSetting"
              :default-expanded-keys="selectedKeys"
              :filter-node-method="handleMenuFilterT2">
              <template #default="{ node, data }">
                <tree-item-name :data="data"></tree-item-name>
              </template>
            </el-tree>

            <h6>已分配-接口权限</h6>
            <el-tree
              ref="selectedtreeT9Ref"
              class="menu-custom-tree tree-empty-image"
              :data="items"
              :check-strictly="true"
              node-key="tid"
              :highlight-current="true"
              :props="treeSetting"
              :default-expanded-keys="selectedKeys"
              :filter-node-method="handleMenuFilterT9">
              <template #default="{ node, data }">
                <tree-item-name :data="data"></tree-item-name>
              </template>
            </el-tree>
          </perfect-scrollbar>
        </div>
      </div>
      <div class="associate-item">
        <div class="associate-item-title">有【{{ form.name }}】角色的管理员：</div>
        <div class="associate-table-wrap">
          <el-table
            class="m-table"
            size="small"
            :data="list"
            height="450"
            row-key="id"
            border
          >
            <el-table-column
              prop="admin.nickname"
              label="昵称">
            </el-table-column>
            <el-table-column
              prop="admin.loginname"
              label="登录名">
            </el-table-column>

            <el-table-column prop="type" label="操作" width="80px">
              <template #default="scope">
                <el-button
                  size="small"
                  type="text"
                  @click="handleRemove(scope.row, scope.$index)">移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, prev, pager, next"
          @size-change="refresh"
          @current-change="refresh">
        </el-pagination>
      </div>
    </div>
    <div class="btns" style="text-align: right;">
      <el-button @click="close()">关 闭</el-button>
    </div>
  </div>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.associate-wrap {
  .associate-body {
    display: flex;
  }

  .associate-item {
    flex: 1;
  }

  .role-menu-tree {
    border: 1px solid #EEE;
    background: #FCFCFC;
    padding: 10px;
    height: 450px;
    margin-right: 10px;
    padding-right: 0px;

    h6 {
      margin-top: 0;
      margin-bottom: 5px;
      font-weight: bold;
    }
  }
}

.associate-table-wrap {
  /*border: 1px solid #EEE;*/

  thead .el-checkbox {
    margin-bottom: 0px;
  }
}

.associate-item-title {
  font-size: 13px;
  color: #999;
  margin-bottom: 10px;
}
</style>
